package com.lx.backstagemanagement.security.auth.login;

import com.alibaba.fastjson.JSON;
import com.lx.backstagemanagement.entity.User;
import com.lx.backstagemanagement.security.model.UserContext;
import com.lx.backstagemanagement.service.impl.UserServiceImpl;
import com.lx.backstagemanagement.util.MD5Utils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.List;


/**
 * @author Levin
 * @since 2017-05-25
 */
@Component
public class LoginAuthenticationProvider implements AuthenticationProvider {

    private Logger logger = LoggerFactory.getLogger(LoginAuthenticationProvider.class);

    final BCryptPasswordEncoder encoder;
    final UserServiceImpl userService;
//	final UserRoleService roleService;

    @Autowired
    public LoginAuthenticationProvider(final UserServiceImpl userService, final BCryptPasswordEncoder encoder) {
        this.userService = userService;
//        this.roleService = roleService;
        this.encoder = encoder;
    }


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.notNull(authentication, "No authentication data provided");
        logger.debug("[authentication info] - [{}]", JSON.toJSONString(authentication));
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        User user1 = new User();
        user1.setUsername(username);
        user1.setPassword(password);
        List<User> login = userService.login(user1);
        User user = login.get(0);
        if (user == null) throw new UsernameNotFoundException("User not found: " + username);
        if (!StringUtils.equals(password, user.getPassword())) {
            throw new BadCredentialsException("Authentication Failed. Username or Password not valid.");
        }
//        List<UserRole> roles = roleService.getRoleByUser(user);
//        if (roles == null || roles.size() <= 0) throw new InsufficientAuthenticationException("User has no roles assigned");
//
//        List<GrantedAuthority> authorities = roles.stream()
//                .map(authority -> new SimpleGrantedAuthority(authority.authority()))
//                .collect(Collectors.toList());
//
        UserContext userContext = UserContext.create(user.getUsername());

        return new UsernamePasswordAuthenticationToken(userContext, null, null);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
